<template>
  <!-- 根据 showCheckbox 属性来决定显示哪个区域 -->
  <ContentWrap>
    <!-- tabs切换 -->
    <el-tabs v-model="activeTab" class="mb-15px" @tab-click="handleTabClick">
      <el-tab-pane
        v-for="item in hazardTypes"
        :key="item.value"
        :label="item.label"
        :name="item.value"
      />
    </el-tabs>

    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="首字母" prop="letter">
        <el-input
          v-model="queryParams.letter"
          class="!w-240px"
          clearable
          placeholder="请输入首字母"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="中文名" prop="cnName">
        <el-input
          v-model="queryParams.cnName"
          class="!w-240px"
          clearable
          placeholder="请输入中文名"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button
          v-hasPermi="['system:hazards:create']"
          plain
          type="primary"
          @click="openForm('create')"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表区域 -->
  <ContentWrap v-if="!showCheckbox">
    <el-table v-loading="loading" :data="list" :show-overflow-tooltip="true" :stripe="true">
      <el-table-column align="center" label="序号" type="index" width="60" />
      <el-table-column align="center" label="危害分类" prop="type">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.HAZARD_TYPE" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="中文名" prop="cnName" />
      <el-table-column align="center" label="首字母" prop="letter" />
      <el-table-column align="center" label="英文名称" prop="enName" />
      <el-table-column align="center" label="操作" min-width="120px">
        <template #default="scope">
          <el-button
            v-hasPermi="['system:hazards:update']"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-hasPermi="['system:hazards:delete']"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 已选中标签展示区域 -->
  <ContentWrap v-if="showCheckbox">
    <div class="mt-15px">
      <div class="mb-10px text-[14px] font-bold">已选择的危害因素：</div>
      <div class="flex flex-wrap gap-2">
        <template v-for="item in internalSelected" :key="item.id">
          <template v-if="item.cnName.includes('、')">
            <el-tag
              v-for="(name, index) in item.cnName.split('、')"
              :key="`${item.id}-${index}`"
              :class="['mr-5px mb-5px', `hazard-type-${item.type}`, 'is-selected']"
              closable
              round
              @close="handleTagClose(item, name)"
            >
              {{ name }}
            </el-tag>
          </template>
          <el-tag
            v-else
            :class="['mr-5px mb-5px', `hazard-type-${item.type}`, 'is-selected']"
            closable
            round
            @close="handleTagClose(item)"
          >
            {{ item.cnName }}
          </el-tag>
        </template>
      </div>
    </div>
  </ContentWrap>

  <!-- 标签选择区域 -->
  <ContentWrap v-if="showCheckbox">
    <div class="mt-15px">
      <div class="mb-10px text-[14px] font-bold flex items-center justify-between">
        <span>危害因素列表：</span>
        <el-button v-if="!showQuickAdd" link type="primary" @click="showQuickAdd = true">
          <Icon icon="ep:plus" />
        </el-button>
      </div>
      <div class="flex flex-wrap gap-2">
        <el-tag
          v-for="item in allHazardsList"
          :key="item.id"
          :class="[
            'mr-5px mb-5px cursor-pointer',
            { 'is-selected': isSelected(item) },
            `hazard-type-${item.type}`
          ]"
          effect="plain"
          round
          @click="handleTagClick(item)"
        >
          {{ item.cnName }}
        </el-tag>
      </div>
    </div>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <HazardsForm ref="formRef" @success="getList" />
</template>

<script lang="ts" setup>
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { HazardsApi, HazardsVO } from '@/api/system/hazards'
import HazardsForm from './HazardsForm.vue'

/** 危害因素 列表 */
defineOptions({ name: 'Hazards' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<HazardsVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

// 定义类型接口
interface HazardType {
  label: string
  value: string
}

// 修改响应式变量的类型声明
const activeTab = ref<string>('') // 当前激活的 tab
const hazardTypes = ref<HazardType[]>([]) // 危害类型选项

// 修改 queryParams 的类型
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  type: '' as string, // 修改为字符串类型，设置初始值
  cnName: undefined as string | undefined,
  letter: undefined as string | undefined,
  enName: undefined as string | undefined,
  cas: undefined as string | undefined,
  mac: undefined as string | undefined,
  pcTwa: undefined as string | undefined,
  pcStel: undefined as string | undefined,
  totalDust: undefined as string | undefined,
  expiratoryDust: undefined as string | undefined,
  healthEffects: undefined as string | undefined
})
const queryFormRef = ref() // 搜索的表单

// 新增：存储所有危害因素的列表
const allHazardsList = ref<HazardsVO[]>([])

// 修改 props 定义，明确类型
const props = defineProps<{
  showCheckbox: boolean
  selectedHazards: Array<{
    id: number
    type: number | string
    cnName: string
    letter?: string
    enName?: string
    cas?: string
    mac?: string
    pcTwa?: string
    pcStel?: string
    totalDust?: string
    expiratoryDust?: string
    healthEffects?: string
    isDeleted?: boolean
    sampling?: {
      sampleDays: number
      pointCount: number
      sampleCount: number
      contactHours: number
      startDay: number
      timeType: 'long' | 'short'
      sampleType: 'fix' | 'personal' | 'none'
      isCustomTime?: boolean
      sampleDuration?: number
    }
  }>
}>()

// 新增 emit 定义
const emit = defineEmits(['select'])

// 修改内部选中状态的类型定义
const internalSelected = ref<typeof props.selectedHazards>([])

// 修改判断是否选中的方法
const isSelected = (item: HazardsVO) => {
  const result = internalSelected.value.some((selected) => {
    // 将已选择的名称按逗号拆分
    const selectedNames = selected.cnName.split('、')
    // 检查当前项的名称是否在已选择的名称列表中
    const isIncluded = selectedNames.includes(item.cnName)
    return isIncluded
  })
  return result
}

// 修改标签点击处理方法
const handleTagClick = (item: HazardsVO) => {
  if (!props.showCheckbox) return

  console.log('点击项', JSON.stringify(item));

  console.log('当前已选择', JSON.stringify(internalSelected.value))

  // 查找是否已存在包含该名称的项
  const index = internalSelected.value.findIndex((selected) => {
    const names = selected.cnName.split('、')
    return names.includes(item.cnName)
  })
  console.log('查找索引:', index)

  if (index > -1) {
    // 如果已经选中，从名称列表中移除
    const names = internalSelected.value[index].cnName.split('、')
    const nameIndex = names.indexOf(item.cnName)
    console.log('名称处理:', {
      当前名称: item.cnName,
      已选择名称列表: names,
      名称索引: nameIndex
    })

    if (nameIndex > -1) {
      names.splice(nameIndex, 1)
      if (names.length > 0) {
        // 如果还有其他名称，更新cnName
        internalSelected.value[index] = {
          ...internalSelected.value[index],
          cnName: names.join('、')
        }
        console.log('更新后的项:', internalSelected.value[index])
      } else {
        // 如果没有其他名称，删除整个项
        internalSelected.value.splice(index, 1)
        console.log('删除整个项')
      }
    }
  } else {
    // 如果未选中，添加新项
    const newItem = {
      id: item.id || 0,
      type: item.type,
      cnName: item.cnName,
      letter: item.letter || '',
      enName: item.enName,
      cas: item.cas,
      mac: item.mac,
      pcTwa: item.pcTwa,
      pcStel: item.pcStel,
      totalDust: item.totalDust,
      expiratoryDust: item.expiratoryDust,
      healthEffects: item.healthEffects
    } as (typeof props.selectedHazards)[0]

    internalSelected.value.push(newItem)
    console.log('添加新项:', newItem)
  }

  console.log('更新后的已选择列表2:', JSON.stringify(internalSelected.value))
  emit('select', [...internalSelected.value])
}

const handleTagClose = (item: (typeof props.selectedHazards)[0], specificName?: string) => {
  console.log('关闭项', JSON.stringify(item))
  console.log('特定名称', JSON.stringify(specificName))

  // 查找包含特定名称的项
  const index = internalSelected.value.findIndex((selected) => {
    const names = selected.cnName.split('、')
    return specificName ? names.includes(specificName) : names.includes(item.cnName)
  })
  console.log('查找索引:', index)

  if (index > -1) {
    const names = internalSelected.value[index].cnName.split('、')
    const nameToRemove = specificName || item.cnName
    const nameIndex = names.indexOf(nameToRemove)
    console.log('名称处理:', {
      要移除的名称: nameToRemove,
      已选择名称列表: names,
      名称索引: nameIndex
    })

    if (nameIndex > -1) {
      names.splice(nameIndex, 1)
      if (names.length > 0) {
        // 更新剩余的名称
        internalSelected.value[index] = {
          ...internalSelected.value[index],
          cnName: names.join('、')
        }
        console.log('更新后的项:', internalSelected.value[index])
      } else {
        // 如果没有剩余名称，删除整个项
        internalSelected.value.splice(index, 1)
        console.log('删除整个项')
      }
    }
    console.log('更新后的已选择列表1:', JSON.stringify(internalSelected.value))
    emit('select', internalSelected.value)
  }
}


// 修改：清除选中状态
const clearGlobalSelected = () => {
  internalSelected.value = []
}

// 暴露方法给父组件
defineExpose({
  clearGlobalSelected
})

// 获取危害类型选项
const getHazardTypes = () => {
  hazardTypes.value = getStrDictOptions(DICT_TYPE.HAZARD_TYPE)
  // 默认选中第一个 tab，并设置初始 type
  if (hazardTypes.value.length > 0) {
    activeTab.value = hazardTypes.value[0].value
    queryParams.type = activeTab.value // 确保初始化时设置 type
  }
}

// tab切换处理
const handleTabClick = async (tab: any) => {
  queryParams.type = tab.props.name
  await Promise.all([handleQuery(), getAllHazards()]) // 同时更新表格和标签数据
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 不需要在这里重新设置 type，因为已经在 tab 切换时设置了
    const data = await HazardsApi.getHazardsPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.pageNo = 1
  await Promise.all([getList(), getAllHazards()]) // 同时更新表格和标签数据
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  // 重置时保留当前选中的类型
  queryParams.type = activeTab.value
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await HazardsApi.deleteHazards(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

// 新增：获取所有危害因素的方法
const getAllHazards = async () => {
  try {
    const data = await HazardsApi.getHazardsPage({
      ...queryParams,
      pageSize: 999, // 设置较大的页面大小以获取所有数据
      pageNo: 1
    })
    allHazardsList.value = data.list
  } catch (error) {
    console.error('获取所有危害因素失败:', error)
  }
}

/** 初始化 **/
onMounted(async () => {
  getHazardTypes() // 获取危害类型选项并设置初始 type
  await Promise.all([getList(), getAllHazards()]) // 同时获取表格和标签数据
})

// 修改：处理标签关闭

// 在 setup 中添加新的响应式变量
const showQuickAdd = ref(false)
const quickAddName = ref('')

// 修改监听器
watch(
  () => props.selectedHazards,
  (newVal) => {
    if (newVal) {
      // 确保深拷贝数组
      internalSelected.value = JSON.parse(JSON.stringify(newVal))
      // internalSelected.value = JSON.parse(JSON.stringify(newVal.filter(x => x.isDeleted==false)))
    }
  },
  { immediate: true, deep: true }
)
</script>

<style lang="scss" scoped>
.el-tag {
  position: relative;
  padding-right: 20px; // 为徽标留出空间

  .reco-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    background-color: var(--el-color-danger);
    color: white;
    font-size: 10px;
    padding: 2px 4px;
    border-radius: 8px;
    transform: scale(0.8);
    white-space: nowrap;
  }

  &.cursor-pointer {
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background-color: var(--el-color-primary-light-8);
    }
  }

  // 选中状态样式
  &.is-selected {
    .el-tag__close {
      color: inherit;

      &:hover {
        color: #fff;
        background-color: currentColor;
      }
    }
  }

  // 不同类型的危害标签颜色
  &.hazard-type-1 {
    // 物理因素
    color: #409eff;
    background-color: #ecf5ff;
    border-color: #d9ecff;

    &.is-selected {
      color: #409eff;
      background-color: #d9ecff;
      border-color: #409eff;
    }
  }

  &.hazard-type-2 {
    // 化学因素
    color: #67c23a;
    background-color: #f0f9eb;
    border-color: #e1f3d8;

    &.is-selected {
      color: #67c23a;
      background-color: #e1f3d8;
      border-color: #67c23a;
    }
  }

  &.hazard-type-3 {
    // 生物因素
    color: #e6a23c;
    background-color: #fdf6ec;
    border-color: #faecd8;

    &.is-selected {
      color: #e6a23c;
      background-color: #faecd8;
      border-color: #e6a23c;
    }
  }

  &.hazard-type-4 {
    // 人体工效
    color: #f56c6c;
    background-color: #fef0f0;
    border-color: #fde2e2;

    &.is-selected {
      color: #f56c6c;
      background-color: #fde2e2;
      border-color: #f56c6c;
    }
  }

  &.hazard-type-5 {
    // 其他
    color: #909399;
    background-color: #f4f4f5;
    border-color: #e9e9eb;

    &.is-selected {
      color: #909399;
      background-color: #e9e9eb;
      border-color: #909399;
    }
  }
}

.quick-add-input {
  width: 200px;

  :deep(.el-input-group__append) {
    padding: 0;

    .el-button {
      margin: 0;
      border: none;
      height: 100%;
      padding: 0 10px;
    }
  }
}
</style>
